package 字符串算法;

public class 替换空格 {
    class Solution{
        /**
         * 第一种方法：常规方法。利用String.charAt(i)以及String.valueOf(char).equals(" "
         * )遍历字符串并判断元素是否为空格。是则替换为"%20",否则不替换
         */

        private  String replaceSpace(StringBuffer str){

            int length = str.length();
            StringBuffer buffer = new StringBuffer();
            for (int i = 0; i < length; i++) {
                char c = str.charAt(i);
                if (String.valueOf(c).equals(" ")){
                    buffer.append("%20");
                }else {
                    buffer.append(c);
                }
            }
            return buffer.toString();
        }

        private  String replaceSpace2(StringBuffer str){
            return str.toString().replaceAll("\\s","%20");

        }

        public  void main(String[] args) {
            StringBuffer stringBuffer = new StringBuffer();
            StringBuffer we_are_happy = stringBuffer.append("We Are Happy");
            String s = replaceSpace(we_are_happy);
            System.out.println(s);
            String s1 = replaceSpace2(we_are_happy);
            System.out.println(s1);
        }

    }


    /**
     * 解法二 使用双指针
     */
    class Solution2{
        public String replaceSpace(String s){
            if (s == null && s.length()==0){
                return s;
            }
            //扩展数组容量
            StringBuffer sb = new StringBuffer();
            char[] ch = s.toCharArray();
            for (int i = 0; i < ch.length; i++) {
                if (ch[i] == ' '){
                    sb.append(" ");
                }
            }
            //没有空格就直接返回去
            if (sb.length() == 0){
                return s;
            }
            //left指向原始数组的最后一位
            int left = s.length() - 1;
            s+=sb.toString();
            //right指向扩展后数组的最后一位
            int right = s.length()- 1;
            char[] chars = s.toCharArray();
            while(left>=0){
                if (chars[left] == ' '){
                    chars[right--] = '0';
                    chars[right--] = '2';
                    chars[right] = '%';
                }else {
                    chars[right] = chars[left];
                }

                left--;
                right--;

            }
            return new String(chars);

        }
    }





}
